<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Traits;

use App\Exports\TablesExport;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Facades\Excel;

trait ExcelTrait
{
    /**
     * @param array $header (表头)
     * @param array|Collection $list (数据)
     * @param string $name (表名)
     * @param array $columnFormat
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function excelExport($header, $list, $name, $columnFormat = [])
    {
        $name = $name . date('YmdHis') . '.xlsx';
        $keys = array_keys($header);
        $result[0] = $header;
        foreach ($list as $k => $v) {
            foreach ($keys as $v2) {
                if (is_array($list)) {
                    $result[$k + 1][$v2] = $v[$v2];
                } else {
                    $result[$k + 1][$v2] = $v->{$v2};
                }
            }
        }
        $result = collect($result);
        return Excel::download(new TablesExport($result, $columnFormat), $name);
    }
}
